<!--
 * @Author: liaoxing
 * @Date: 2021-11-11 11:24:19
 * @LastEditors: liaoxing
 * @LastEditTime: 2021-12-22 14:05:31
 * @Description: liaoxing created
 * @FilePath: \品新集成管理系统\pin-xin-admin\src\views\report\design.vue
-->
<template>
  <div class="dataReport">
    <div class="categoryBox">
      <div class="categoryHeaderBox flex">
        <span style="font-weight: 600">目录</span>
        <el-tooltip class="iconTip" effect="dark" content="新增目录" placement="right">
          <i class="el-icon-plus" @click="appendCategory()"></i>
        </el-tooltip>
      </div>
      <el-tree
        v-loading="loading"
        :data="categoryList"
        :props="defaultProps"
        node-key="id"
        @node-click="handleNodeClick"
        :filter-node-method="filterNode"
        :highlight-current="true"
        ref="reportTree"
        default-expand-all
      >
        <span class="custom-tree-node" slot-scope="{ node, data }">
          <span style="width: 80%" class="more" :class="{'color-blue': !node.parent.parent}">
            <span class="jstarfont" :class="{'jstar-wenjianjia': !node.parent.parent}" :style="{marginRight: !node.parent.parent? '5px' : '5px'}"></span>
            <el-tooltip :content="node.label" placement="top" effect="dark">
              <span>{{ node.label }}</span>
            </el-tooltip>
          </span>
          <span class="reportIconBox">
            <el-popover
              :popper-class="'reportPopover'"
              placement="bottom"
              width="30"
              trigger="hover">
              <div class="popBox">
                <el-tooltip v-if="data.pid === '0'" class="item" effect="dark" content="新增子目录" placement="right">
                  <i class="el-icon-plus" @click.stop.prevent="appendCategory(data)"></i>
                </el-tooltip>
                <i class="el-icon-delete" @click.stop.prevent="deleteCategory(data)"></i>
                <i class="el-icon-edit-outline" @click.stop.prevent="editCategory(data)"></i>
              </div>
              <span slot="reference" class="jstarfont jstar-gengduo finger"></span>
            </el-popover>
            <!-- <el-tooltip v-if="data.pid === '0'" class="item" effect="dark" content="新增类别" placement="bottom">
              <i class="el-icon-plus" @click.stop.prevent="appendCategory(data)"></i>
            </el-tooltip>
            <i class="el-icon-delete" @click.stop.prevent="deleteCategory(data)"></i>
            <i class="el-icon-edit-outline" @click.stop.prevent="editCategory(data)"></i> -->
          </span>
        </span>
      </el-tree>
      <!-- <div class="addCategoryBtnBox flex flex-center">
        
      </div> -->
    </div>
    <div class="reportBox">
      <contentNavModule
        @resetReportList="resetReportList"
        @addReports="addReport"
        @searchList="searchList"
      ></contentNavModule>
      <div class="contentBox">
        <!-- <template v-if="!modeType">
          <div class="addBox flex flex-center">
            <el-tooltip content="新建报表" placement="top" effect="dark">
              <span class="jstarfont jstar-xinzeng" @click="addReport"></span>
            </el-tooltip>
          </div>
          <viewBox v-for="item in 2" :key="'viewBox' + item"></viewBox>
        </template> -->
        <template>
          <el-table
            v-loading="loading2"
            :data="dataList"
            border
            stripe
            height="675"
            style="width: 100%;">
            <el-table-column
              prop="name"
              label="报表名称">
            </el-table-column>
            <el-table-column
              prop="create_by"
              label="创建人"
              width="70">
            </el-table-column>
            <el-table-column
              prop="create_time"
              label="创建时间"
              width="150">
            </el-table-column>
            <el-table-column
              label="被授权人">
              <template slot-scope="scope">
                <span>{{ getStrName(scope.row.members) }}</span>
              </template>
            </el-table-column>
            <el-table-column
              prop="view_count"
              label="查看次数"
              width="80">
            </el-table-column>
            <el-table-column
              label="操作"
              width="110">
              <template slot-scope="scope">
                <el-tooltip content="查看编辑" placement="top" effect="dark">
                  <span class="jstarfont jstar-yanjing finger" @click="preview(scope.row)"></span>
                </el-tooltip>
                <!-- <el-tooltip content="收藏" placement="top" effect="dark">
                  <span class="jstarfont" :class="{'jstar-jushoucang': !scope.row.collectStatus, 'jstar-jushoucanggift': scope.row.collectStatus, 'color-red': scope.row.collectStatus}"></span>
                </el-tooltip> -->
                <el-tooltip content="删除" placement="top" effect="dark">
                  <span class="jstarfont jstar-shanchutianchong finger" @click="deleteReport(scope.row.id)"></span>
                </el-tooltip>
                <!-- <el-tooltip content="复制" placement="top" effect="dark">
                  <span class="jstarfont font12 jstar-fuzhiwenjian"></span>
                </el-tooltip> -->
                <el-tooltip content="修改目录" placement="top" effect="dark">
                  <span class="jstarfont jstar-mulu finger" @click="changeCategory(scope.row)"></span>
                </el-tooltip>
                <el-tooltip content="授权" placement="top" effect="dark">
                  <span class="jstarfont jstar-fenxiang finger" @click="openAuthorizeBox(scope.row)"></span>
                </el-tooltip>
              </template>
            </el-table-column>
          </el-table>
        </template>
      </div>
      <el-pagination
        style="float: right"
        :current-page.sync="pageNum"
        :page-size="pageSize"
        layout="total, prev, pager, next, jumper"
        :total="totalSize">
      </el-pagination>
    </div>
    <el-dialog :title="isEdit ? '修改目录' : '新增目录'" :visible.sync="dialogFormVisible" width="30%">
      <el-form :model="addInfo" :rules="addInfoRules" ref="addInfo">
        <el-form-item label="目录名称" :label-width="'80px'" prop="name">
          <el-input v-model="addInfo.name" autocomplete="off"></el-input>
        </el-form-item>
        <!-- <el-form-item label="pid" :label-width="'80px'" prop="pid">
          <el-input v-model="addInfo.pid" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="id" :label-width="'80px'" prop="id">
          <el-input v-model="addInfo.id" autocomplete="off"></el-input>
        </el-form-item> -->
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitForm('addInfo')">确 定</el-button>
      </div>
    </el-dialog>
    <el-dialog title="请选择被授权人" :visible.sync="openAuthorize" width="40%">
      <selectMemberTree :currentReportUser="currentReportUser" :openAuth="openAuthorize" @confirmAuthorize="confirmAuthorize"></selectMemberTree>
    </el-dialog>
    <el-dialog title="请选择目录" :visible.sync="openChangeCategory" width="20%">
      <el-tree
        v-loading="loading"
        :data="categoryList"
        :props="defaultProps"
        node-key="id"
        show-checkbox
        ref="reportTree2"
        :check-strictly="true"
        default-expand-all
        @check-change="checkChange"
      >
        <span class="custom-tree-node" slot-scope="{ node }">
          <span class="more" :class="{'color-blue': !node.parent.parent}">
            {{ node.label }}
          </span>
        </span>
      </el-tree>
      <div style="height: 40px; text-align: center; margin-top: 20px">
        <el-button type="primary" @click="confirmChange">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import selectMemberTree from "@/components/selectMemberTree/selectMemberTree"
import contentNavModule from '@/components/contentNavModule/contentNavModule.vue'
export default {
  components: { contentNavModule, selectMemberTree },
  name: "dataReport",
  data () {
    return {
      categoryList: null,
      currentCategoryId: null,
      defaultProps: {
        children: 'children',
        label: 'name'
      },
      filterText: '',
      dialogFormVisible: false,
      addInfo: {
        name: '',
        pid: '',
        id: ''
      },
      addInfoRules: {
        name: [
          { required: true, message: '请输入名称', trigger: 'change' }
        ]
      },
      /* 报表模块 */
      modeType: 1,
      dataList: [],
      /* 新建报表 */
      menuitem: "datainfo",
      addUrl: "/jmreport/index/",
      /* 编辑报表 */
      isEdit: false,
      /* 报表授权 */
      openAuthorize: false,
      currentReportId: '',
      currentReportUser: [],
      loading: false,
      loading2: false,
      pageNum: 1,
      pageSize: 10,
      totalSize: 0,
      /* 搜索信息 */
      searvhValue: {
        name: '',
        crearter: ''
      },
      /* 当前用户id */
      userId: 1,
      /* 公司成员 */
      personList: null,
      /* 报表修改目录 */
      openChangeCategory: false,
      currentChangeCategoryId: null,
      checkedId: null,
    }
  },
  watch: {
    filterText(val) {
      this.$refs.reportTree.filter(val);
    },
    dialogFormVisible (val) {
      if (!val) {
        this.resetForm('addInfo')
      }
    },
    pageNum: {
      deep: true,
      handler: function () {
        this.queryAllReportByType()
      }
    }
  },
  computed: {
  },
  created () {
    this.getPersonList()
  },
  methods: {
    /* 确认报表目录修改 */
    confirmChange () {
      let params = {
        type: this.checkedId
      }
      this.$report.changeCategory(this.currentChangeCategoryId, params)
        .then(res => {
          if (res.code === 200) {
            this.$message.success("修改成功")
            this.queryAllReportByType()
            this.openChangeCategory = false
          } else {
            this.$message.error(res.code + '-' + res.msg)
          }
        })
        .catch(e => {
          this.$message.error(e.toString())
        })
    },
    /* 选中节点 */
    checkChange (item, checked) {
      if(checked === true) {
        this.checkedId = item.id
        this.$refs.reportTree2.setCheckedKeys([item.id])
      } else {
        if (this.checkedId == item.id) {
          this.$refs.reportTree2.setCheckedKeys([item.id])
        }
      }
    },
    /* 表修改目录 */
    changeCategory (item) {
      this.currentChangeCategoryId = item.id
      this.openChangeCategory = true
      this.$nextTick(() => {
        this.$refs.reportTree2.setCheckedKeys([item.type])
      })
    },
    /* 获取公司人员 */
    getPersonList () {
      this.$report.userList()
        .then(res => {
          if (res.code === 200) {
            this.personList = res.data
          } else {
            this.$message.error(res.code + '-' + res.msg)
          }
          this.getCatalogue()
        })
        .catch(e => {
          this.$message.error(e.toString())
        })
    },
    /* 根据id获取名称 */
    getStrName (idList) {
      if(!idList || !idList.length) return ''
      let strName = []
      idList.forEach(element => {
        let item = this.personList.find(item => item.id == element)
        if (item) {
          strName.push(item.username)
        } else {
          strName.push('未知用户')
        }
      })
      return strName.join("、")
    },
    // /* 切换视图 */
    // changeMode (type) {
    //   this.modeType = type
    // },
    // /* 切换页面 */
    // changePage (pageNum) {
    //   console.log(pageNum)
    // },
    /* 重置列表 */
    resetReportList (searvhValue) {
      this.searvhValue = searvhValue
      this.pageNum = 1
      this.queryAllReportByType()
    },
    /* 搜索数据 */
    searchList (searvhValue) {
      this.searvhValue = searvhValue
      this.pageNum = 1
      this.queryAllReportByType()
    },
    /* 新建报表 */
    addReport () {
      this.$report.addReport()
        .then(res => {
          window.open(window.repoortURL + this.addUrl + res.result.id + "?tpye=" + this.currentCategoryId)
        })
    },
    /* 预览报表 */
    preview (item) {
      window.open(window.repoortURL + this.addUrl + item.id + "?type=" + item.type)
    },
    /* 分类树点击 */
    handleNodeClick(data) {
      this.currentCategoryId = data.id
      this.queryAllReportByType()
    },
    /* 树搜索过滤 */
    filterNode(value, data) {
      if (!value) return true;
      return data.name.indexOf(value) !== -1;
    },
    /* 获取目录 */
    getCatalogue () {
      this.loading = true
      this.$report.catalogue()
        .then(res => {
          if (res.code === 200) {
            this.categoryList = res.data
            this.$nextTick(() => {
              // setCurrentKey
              this.$refs.reportTree.setCurrentKey(res.data[0].id)
              this.currentCategoryId = res.data[0].id
              this.queryAllReportByType()
            })
          } else {
            this.$message.error(res.code + '-' + res.msg)
          }
          this.loading = false
        })
        .catch(e => {
          this.$message.error(e.toString())
        })
    },
    nameToTitle (list) {
      if (!list || !list.length) return
      for(let item of list) {
        item.title = item.name
        if (item.children) {
            this.nameToTitle(item.children)
        }
      }
    },
    /* 提交创建类别 */
    submitForm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          let params = JSON.parse(JSON.stringify(this[formName]))
          if (params.pid === '0') {
            delete params.pid
          }
          if (!params.id) {
            delete params.id
          }
          let apiName = this.isEdit ? "editCatalogue" : "addCatalogue"
          this.$report[apiName](params)
            .then(res => {
              if (res.code === 200) {
                console.log(res)
                this.dialogFormVisible = false
                this.getCatalogue()
                this.resetForm(formName)
              } else {
                this.$message.error(res.code + '-' + res.msg)
              }
            })
            .catch(e => {
              this.$message.error(e.toString())
            })
        } else {
          console.log('error submit!!');
          return false;
        }
      });
    },
    /* 清空创建类别 */
    resetForm(formName) {
      this.$refs[formName].resetFields()
      this[formName].name = ''
      this[formName].pid = ''
      this[formName].id = ''
    },
    /* 新建目录 */
    appendCategory (data) {
      this.isEdit = false
      if (data) {
        this.addInfo.pid = data.id
      } else {
        this.addInfo.pid = ''
      }
      this.dialogFormVisible = true
    },
    /* 删除目录 */
    deleteCategory (data) {
      this.$confirm('是否删除 ' + data.name + ' 目录?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.$report.deleteCatalogue(data.id)
          .then(res => {
            if (res.code === 200) {
              this.$message.success("删除" + data.name + "成功！")
              this.getCatalogue()
            } else {
              this.$message.error(res.code + '-' + res.msg)
            }
          })
          .catch(e => {
            this.$message.error(e.toString())
          })
      }).catch(() => {         
      })
    },
    /* 修改目录 */
    editCategory (data) {
      this.isEdit = true
      this.addInfo.pid = data.pid
      this.addInfo.id = data.id
      this.addInfo.name = data.name
      this.dialogFormVisible = true
    },
    /* 查询类别报表 */
    queryAllReportByType () {
      this.loading2 = true
      let params = {
        type: this.currentCategoryId,
        pn: this.pageNum,
        ps: this.pageSize,
        name_like: this.searvhValue.name,
        create_by_like: this.searvhValue.creater
      }
      if (!this.searvhValue.name) {
        delete params.name_like
      }
      if (!this.searvhValue.creater) {
        delete params.create_by_like
      }
      this.$report.queryAllReportByType(params)
        .then(res => {
          if (res.code === 200) {
            this.dataList = res.data.rows
            this.totalSize = res.data.total * 1
          } else if (res.code === 500) {
            this.dataList = []
            this.$message.info("报表为空！")
          } else {
            this.$message.error(res.code + '-' + res.msg)
          }
          this.loading2 = false
        })
        .catch(e => {
          this.$message.error(e.toString())
        })
    },
    /* 打开授权弹窗 */
    openAuthorizeBox (data) {
      this.openAuthorize = true
      this.currentReportId = data.id
      this.currentReportUser = data.members
    },
    /* 确认授权 */
    confirmAuthorize (list) {
      // this.$report.authorizeReport(this.currentReportId, encodeURIComponent('[' + list.toString() + ']'))
      this.$report.authorizeReport(this.currentReportId, {userId: list})
        .then(res => {
          if (res.code === 200) {
            this.$message.success("授权成功！")
            this.openAuthorize = false
            this.queryAllReportByType()
          } else {
            this.$message.error(res.code + '-' + res.msg)
          }
        })
        .catch(e => {
          this.$message.error(e.toString())
        })
    },
    /* 删除报表 */
    deleteReport (id) {
      this.$confirm('此操作将删除该报表, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.$report.deleteReport(id)
          .then(res => {
            if (res.code === 200) {
              this.$message.success("删除成功！")
              this.queryAllReportByType()
            } else {
              this.$message.error(res.code + '-' + res.msg)
            }
          })
          .catch(e => {
            this.$message.error(e.toString())
          })
        }).catch(() => {         
      })
    }
  }
}
</script>

<style lang="less">
.reportPopover{
  min-width: 0px;
  .popBox{
    display: flex;
    flex-direction: column;
    // justify-content: space-between;
    align-items: center;
    // height: 60px;
    i{
      margin-bottom: 10px;
    }
  }
}
.dataReport{
  box-sizing: border-box;
  width: 100%;
  height: calc(100vh - 85px);
  .el-tree-node__children{
    font-size: 12px;
  }

  .el-tree-node__content{
    height: 40px;
    line-height: 40px;
    font-size: 13px;
  }

  .el-checkbox__input.is-disabled .el-checkbox__inner{
    display: none;
  }
  .categoryBox{
    box-shadow: 0 0 2px 1px rgb(199, 199, 199);
    overflow: auto;
    width: 200px;
    height: 100%;
    float: left;
    background-color: white;
    .categoryHeaderBox{
      height: 60px;
      padding-left: 22px;
      // line-height: 60px;
      align-items: center;
      font-size: 24px;
      position: relative;
      .iconTip{
        position: absolute;
        right: 10px;
        font-size: 16px;
        color: #409EFF;
      }
    }
    .el-tree{
      margin-top: 0;
    }
    .el-tree-node__content{
      position: relative;
    }
    .custom-tree-node {
      flex: 1;
      display: flex;
      align-items: center;
      justify-content: space-between;
      font-size: 14px;
      padding-right: 8px;
      
      width: 160px;
      .reportIconBox{
        position: absolute;
        right: 5px;
        i{
          margin: 0 3px;
        }
      }
    }
    .addCategoryBtnBox{
      height: 40px;
      width: 100%;
      i{
        font-size: 18px;
        font-weight: 600;
        color: #409EFF;
        cursor: pointer;
      }
    }
  }
  .reportBox{
    overflow: hidden;
    height: 100%;
    box-sizing: border-box;
    padding: 16px;
    .contentBox{
      height: calc(100% - 150px);
      overflow: auto;
      .addBox{
        height: 170px;
        width: 230px;
        margin: 16px;
        box-sizing: border-box;
        border-radius: 6px;
        box-shadow: 0 0 2px rgb(168, 168, 168);
        .jstarfont{
          font-size: 66px;
          color: #409EFF;
        }
        &:hover{
          box-shadow: 0 0 6px #409EFF;
        }
      }
      .jstarfont{
        margin: 0 3px;
      }
      .addBox2{
        height: 40px;
        width: 100%;
      }
      &>div{
        float: left;
      }
    }
  }
}
</style>